﻿using daonaite.core.Attribute;
using daonaite.Model.system.dept;
using daonaite.Model.system.menu;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace daonaite.DAL.system
{
    [AutoLoad]
    public class D_dept
    {
        private readonly ISqlSugarClient client;

        public D_dept(ISqlSugarClient client)
        {
            this.client = client;
        }

        /// <summary>
        /// 查询树形部门
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<List<sys_dept>?> gettreedept(Dto_dept data)
        {
            var expable = Expressionable.Create<sys_dept>();
            expable.And(c => c.deleteFlag == "N");

            expable.AndIF(!string.IsNullOrEmpty(data.deptName), c => c.deptName!.Contains(data.deptName!));
            expable.AndIF(data.fid > 0, c => c.fid == data.fid);
            var exp = expable.ToExpression();
            List<sys_dept> treeDept = await client.Queryable<sys_dept>().Where(exp).ToTreeAsync(it => it.child, it => it.fid, 0);

            return treeDept;
        }

        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<int> add(sys_dept data)
        {
            return await client.Insertable(data).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
        }

        /// <summary>
        /// 根据id获取部门信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<sys_dept> getAsync(int id)
        {
            return await client.Queryable<sys_dept>().FirstAsync(it => it.id == id);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<int> updateAsync(sys_dept data)
        {
            return await client.Updateable(data).IgnoreColumns(ignoreAllNullColumns: true)
                   .WhereColumns(it => new { it.id }).ExecuteCommandAsync();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> delete(int id)
        {
            return await client.Updateable<sys_dept>().SetColumns(s => s.deleteFlag == "Y").Where(x => x.id == id).ExecuteCommandAsync();
        }
    }
}
